package org.softmed.rest.server.defaults.generation;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.util.GroovyScriptEngine;
import java.io.File;
import java.util.List;
import org.softmed.filehandling.FileUtil;
import org.softmed.rest.generation.scafold.AppConfig;
import org.softmed.rest.generation.scafold.build.ApplicationProcessor;

import com.google.inject.Inject;

public class DefaultApplicationConfigReader implements ApplicationProcessor {

	@Inject
	GroovyScriptEngine groovyScriptEngine;

	@Inject
	GroovyClassLoader groovyClassLoader;

	FileUtil util = new FileUtil();

	String fileName = "config.groovy";

	@Override
	public void process(List<AppConfig> apps) throws Throwable {
		for (AppConfig app : apps) {
			readConfig(app);
		}
		System.out.println("App configurations read");

	}

	private void readConfig(AppConfig app) throws Throwable {
		File root = new File(app.getPath());
		File[] files = root.listFiles();
		for (File file : files) {
			if (file.isFile() && file.getName().equals(fileName))
				try {
					readAppConfig(file, app);
				} catch (Throwable t) {
					t.printStackTrace();
				}
		}

	}

	private void readAppConfig(File file, AppConfig app) throws Throwable {
		String script = util.readFromFile(file);

		List<Class> classes = app.getClasses();
		String importSnippet = "";
		// for (Class type : classes) {
		// importSnippet += "import " + type.getCanonicalName() + ";\n";
		// }
		script = importSnippet + script;

		Binding binding = new Binding();
		GroovyShell shell = new GroovyShell(groovyClassLoader, binding);

		shell.evaluate(script);

		readVariables(binding, app);

	}

	private void readVariables(Binding binding, AppConfig app) {

		String name = null;
		boolean value;
		try {
			value = (Boolean) binding.getVariable("generate");
			app.setGenerateService(value);
		} catch (Throwable t) {
			// t.printStackTrace();
		}

		try {
			value = (Boolean) binding.getVariable("refactor");
			app.setRefactor(value);
		} catch (Throwable t) {
			// t.printStackTrace();
		}

		try {
			value = (Boolean) binding.getVariable("store");
			app.setStoreREST(value);
		} catch (Throwable t) {
			// t.printStackTrace();
		}

		try {
			name = (String) binding.getVariable("context");
			app.setRestContext(name);
		} catch (Throwable t) {
			// t.printStackTrace();
		}

	}

}
